package com.baizhi.controller;

import com.baizhi.entity.Banner;
import com.baizhi.service.BannerService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpSession;
import java.io.File;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;
import java.util.UUID;

@Controller
@RequestMapping("/banner")
public class BannerController {
    @Autowired
    private BannerService bannerService;

    @RequestMapping("/selectBannerDatagrid")
    @ResponseBody
    public Map selectBannerDatagrid(int page,int rows){
        return bannerService.selectBannerDatagrid(page,rows);
    }

    @RequestMapping("/addBanner")
    @ResponseBody
    public Map addBanner(MultipartFile mf,Banner banner, HttpSession session){

        Map map=new HashMap();
        //获取文件路径
        String path=session.getServletContext().getRealPath("/img/");
        //若目录不存在，创建该目录
        File file=new File(path);
        if(!file.exists()){
            file.mkdirs();
        }
        //获取老名字
        String oldName=mf.getOriginalFilename();
        String newName= UUID.randomUUID().toString()+oldName.substring(oldName.lastIndexOf("."));
        //相对路径
        String realPath="/img/"+newName;
        //绝对路径
        String absolPath=session.getServletContext().getRealPath(realPath);

        try {
            mf.transferTo(new File(absolPath));
            //把拍轮播图对象添加到数据库表里面
            banner.setBannerImageUrl(realPath);
            bannerService.addBanner(banner);
            map.put("isAdd",true);
        } catch (IOException e) {
            e.printStackTrace();
            map.put("isAdd",false);
        }
        return map;
    }

    @RequestMapping("/deleteSomeBanners")
    @ResponseBody
    public Map deleteSomeBanners(int[] ids){
        Map map=new HashMap();
        try {
            bannerService.deleteSomeBanners(ids);
            map.put("isDelete",true);
        } catch (Exception e) {
            e.printStackTrace();
            map.put("isDelete",false);
        }
        return map;
    }
}
